package com.hh.TreeQuestions;

import java.util.*;

/**
 * @Author hanghao
 * @Date 2023/7/3 12:03
 * @Version 1.0
 * 二叉树的层序遍历Ⅱ ()
 * middle
 * 因为是要求自底向上的层序遍历 所以用栈来 存储每层的list 最后再从栈中取出来的时候就是自底向上的了
 */

public class No107 {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if(root == null) return list;
        TreeNode cur = root;
        Stack<List<Integer>> stack = new Stack<>();
        Deque<TreeNode> deque = new LinkedList<>();
        deque.offer(root);
        while (!deque.isEmpty()) {
            int len = deque.size();
            ArrayList<Integer> list1 = new ArrayList<>();
            while (len > 0) {
                TreeNode node = deque.poll();
                list1.add(node.val);
                if(node.left != null) {
                    deque.offer(node.left);
                }
                if(node.right != null) {
                    deque.offer(node.right);
                }
                len--;
            }
            stack.push(list1);
        }
        while (!stack.isEmpty()) {
            List<Integer> res = stack.pop();
            list.add(res);
        }
        return list;
    }
}
